<?php

namespace app\admin\model\tongcheng;

use addons\tongcheng\enum\PlatformBalanceKind;
use addons\tongcheng\model\BaseModel;
use think\Db;

class PlatformBalanceModel extends BaseModel
{

    // use SoftDelete;


    // 表名
    protected $name = 'tongcheng_platform_balance';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    /**
     * 获取平台余额
     * @return RiderBalanceModel|null
     * @throws \think\exception\DbException
     */
    public static function getBalance()
    {
        $balance = self::find();
        if (!$balance) {
            $balance = self::create([
                'balance'                       => 0,
                'total_base_fee'                => 0,
                'total_delivery_fee'            => 0,
                'total_rider_withdraw_hand_fee' => 0,
                'total_zone_withdraw_hand_fee'  => 0,
                'total_rider_withdraw'          => 0,
                'total_zone_withdraw'           => 0,
            ]);
        }

        return $balance;
    }

    /**
     * 平台余额增加
     * @param $zone_id
     * @param $user_id
     * @param $rider_id
     * @param $kind
     * @param $amount
     * @param $changeable
     * @param $memo
     * @return RiderBalanceModel
     */
    public static function increment($zone_id, $user_id, $rider_id, $kind, $amount, $changeable, $memo = '')
    {
        if ($amount <= 0) {
            return null;
        }

        if (!in_array($kind, PlatformBalanceKind::INC_KINDS)) {
            throw new \Exception('不支持的平台财务增加类型：' . $kind);
        }

        $memo = $memo ?: PlatformBalanceKind::getDescription($kind);
        return Db::transaction(function () use ($zone_id, $user_id, $rider_id, $kind, $amount, $changeable, $memo) {
            $balance = self::getBalance();

            $before = $balance['balance'];
            $balance->setInc('balance', $amount);

            // 统计值
            switch ($kind) {
                case PlatformBalanceKind::BASE_FEE:
                    $balance->setInc('total_base_fee', $amount);
                    break;
                case PlatformBalanceKind::DELIVERY:
                    $balance->setInc('total_delivery_fee', $amount);
                    break;
                case PlatformBalanceKind::RIDER_WITHDRAW_HAND_FEE:
                    $balance->setInc('total_rider_withdraw_hand_fee', $amount);
                    break;
                case PlatformBalanceKind::ZONE_WITHDRAW_HAND_FEE:
                    $balance->setInc('total_zone_withdraw_hand_fee', $amount);
                    break;
                default:
                    break;
            }

            // 添加余额变动记录
            PlatformBalanceLogModel::create([
                'zone_id'         => $zone_id,
                'user_id'         => $user_id,
                'rider_id'        => $rider_id,
                'type'            => 'INC',
                'kind'            => $kind,
                'amount'          => $amount,
                'before'          => $before,
                'after'           => $balance['balance'],
                'changeable_id'   => $changeable['id'],
                'changeable_type' => get_class($changeable),
                'memo'            => $memo,
            ]);
            return $balance;
        });
    }

    /**
     * 平台余额减少
     * @param $zone_id
     * @param $user_id
     * @param $rider_id
     * @param $kind
     * @param $amount
     * @param $changeable
     * @param $memo
     * @return RiderBalanceModel
     */
    public static function decrement($zone_id, $user_id, $rider_id, $kind, $amount, $changeable, $memo = '')
    {
        if ($amount <= 0) {
            return null;
        }

        if (!in_array($kind, PlatformBalanceKind::DEC_KINDS)) {
            throw new \Exception('不支持的平台财务扣减类型：' . $kind);
        }

        $balance = self::getBalance($zone_id);
        // if ($balance['balance'] < $amount) {
        //     throw new \Exception('平台余额不足');
        // }

        $memo = $memo ?: PlatformBalanceKind::getDescription($kind);
        return Db::transaction(function () use ($zone_id, $user_id, $rider_id, $kind, $amount, $changeable, $memo, $balance) {
            $before = $balance['balance'];
            $balance->setDec('balance', $amount);

            // 统计值
            switch ($kind) {
                case PlatformBalanceKind::RIDER_WITHDRAW:
                    $balance->setInc('total_rider_withdraw', $amount);
                    break;
                case PlatformBalanceKind::ZONE_WITHDRAW:
                    $balance->setInc('total_zone_withdraw', $amount);
                    break;
                default:
                    break;
            }

            // 添加余额变动记录
            PlatformBalanceLogModel::create([
                'zone_id'         => $balance['zone_id'] ?? 0,
                'user_id'         => $user_id,
                'rider_id'        => $rider_id,
                'type'            => 'DEC',
                'kind'            => $kind,
                'amount'          => $amount * -1,
                'before'          => $before,
                'after'           => $balance['balance'],
                'changeable_id'   => $changeable['id'],
                'changeable_type' => get_class($changeable),
                'memo'            => $memo,
            ]);
            return $balance;
        });
    }
}
